package com.lottery.material.util;

import com.lottery.material.pojocustom.portaluser.PortalUserInfoCustom;
import org.apache.commons.collections.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description：前端用户信息导出Excel缓存工具类
 * Created by 朱正磊 on 2019-06-05 15:24
 */
public class PortalUserInfoExportCacheUtil {

    //定义用来缓存的Map
    public static Map<String, List<PortalUserInfoCustom>> portalUserInfoExportCacheMap = new HashMap<>();

    /**
     * description：分段获取数据列表
     * user 朱正磊
     * time 2019-06-05 15:30
     * @param key 缓存key
     * @param start 开始索引（包括）
     * @param end 结束索引（不包括）
     * @return 返回数据列表
     */
    public static List<PortalUserInfoCustom> getGeneralPortalUserInfoList(String key, int start, int end) {
        List<PortalUserInfoCustom> generalPortalUserInfoList;
        if (portalUserInfoExportCacheMap.containsKey(key)) {
            generalPortalUserInfoList = portalUserInfoExportCacheMap.get(key);
            if (!CollectionUtils.isEmpty(generalPortalUserInfoList) && generalPortalUserInfoList.size() > start && end > start) {
                if (generalPortalUserInfoList.size() >= end) {
                    return generalPortalUserInfoList.subList(start, end);
                } else if (generalPortalUserInfoList.size() < end) {
                    return generalPortalUserInfoList.subList(start, generalPortalUserInfoList.size());
                }
            }
        }
        return null;
    }

    /**
     * description：根据缓存key删除缓存数据
     * user 朱正磊
     * time 2019-06-05 15:28
     * @param key 缓存key
     */
    public static void deleteListByKey(String key) {
        if (portalUserInfoExportCacheMap.containsKey(key)) {
            portalUserInfoExportCacheMap.remove(key);
        }
        for (Map.Entry<String, List<PortalUserInfoCustom>> entry : portalUserInfoExportCacheMap.entrySet()) {
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
            String entryKey = entry.getKey();
            String entryKeyTime = entryKey.split("-")[1];
            //清除超过半个小时的缓存数据，删除失败的补偿机制
            if (System.currentTimeMillis() - (Long.parseLong(entryKeyTime)) >= 30 * 60 * 1000) {
                portalUserInfoExportCacheMap.remove(entryKey);
            }
        }
    }

}
